const ModbusRTU = require('modbus-serial');

let history = [];
let io = {};
const hf2211_tcp_server = '192.168.10.220';

let client = new ModbusRTU();
client.connectTCP(hf2211_tcp_server, { port: 8899 });

// 间隔读
// list of meter's id
const metersIdList = [1, 2, 3, 4, 5, 9, 10, 11, 12, 13, 14];
const motor_name = {
    1: 'T4 1#',
    2: 'T4 2#',
    3: 'T4 3#',
    4: 'T4 4#',
    5: 'T4 5#',
    9: 'T6 1#',
    10: 'T6 2#',
    11: 'T6 3#',
    12: 'T6 4#',
    13: 'T6 5#',
    14: 'T6 6#',
};
const controller_status = {
    0: '停机',
    1: '起动',
    2: '运行',
    3: '正在停车',
    4: '检测到故障',
    5: '故障跳闸'
}
const idx_status = 17;

const getMetersValue = async (meters) => {
    try {
        // 列表循环
        for (let meter of meters) {
            // 读值
            await getMeterValue(meter);
            // 等500ms
            await sleep(10000);
        }
    } catch (e) {
        console.log(e)
    } finally {
        // 重复
        setImmediate(() => {
            getMetersValue(metersIdList);
        })
    }
}

const getMeterValue = async (id) => {
    try {
        let val = {};
        // 设站点号
        await client.setID(id);
        // 读值
        await client.readHoldingRegisters(0x0100, 0x12, function (error, data) {
            val['id'] = id;

            let array_1 = data.data;
            array_1.forEach(function (el, idx, arr) {
                if (idx == arr.length - 1) return;
                arr[idx] = el / 10;
            });
            array_1[11] *= 10;  // 热容值
            //array_1[16] /= 10;  // 电流不平衡0.1%

            val['data'] = array_1;
            val['status'] = controller_status[data.data[idx_status]];
            io.emit('f1_t4-6_fan', val);
            console.log(val);
        });
        // 返回值
        return val;
    } catch (e) {
        // if error return -1
        return e;
    }
}

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));


// 开始读值
getMetersValue(metersIdList);

client.set_socketio = function (socket_io) {
    io = socket_io;
}




module.exports = client;